<template>
  <div class="dish-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <input 
        v-model="searchText" 
        placeholder="搜索菜品..." 
        @input="handleSearch"
      >
    </div>

    <!-- 菜品列表 -->
    <div class="dish-list">
      <div 
        v-for="dish in filteredDishes" 
        :key="dish.dishId" 
        class="dish-card"
        @click="showPurchaseDialog(dish)"
      >
        <div class="dish-image" :style="{ backgroundImage: `url(${dish.imageUrl || defaultImage})` }"></div>
        <div class="dish-info">
          <h3>{{ dish.dishName }}</h3>
          <p class="dish-price">¥{{ dish.price.toFixed(2) }}</p>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="!loading && dishes.length === 0" class="empty">暂无菜品数据</div>

    <!-- 购买对话框 -->
    <el-dialog
      v-model="purchaseDialogVisible"
      :title="`购买 ${selectedDish?.dishName}`"
      width="90%"
    >
      <div v-if="selectedDish" class="purchase-dialog">
        <div class="dish-info">
          <img :src="selectedDish.imageUrl || defaultImage" class="dialog-dish-image">
          <div class="dish-details">
            <h3>{{ selectedDish.dishName }}</h3>
            <p class="price">价格: ¥{{ selectedDish.price.toFixed(2) }}</p>
          </div>
        </div>
        
        <div class="form-group">
          <label>数量</label>
          <el-input-number v-model="quantity" :min="1" :max="10" />
        </div>
        
        <div class="form-group">
          <label>配送地址</label>
          <el-select v-model="selectedAddressId" placeholder="请选择配送地址">
            <el-option
              v-for="address in userAddresses"
              :key="address.addressId"
              :label="address.specificLocation"
              :value="address.addressId"
            />
          </el-select>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmPurchase" 
            :loading="orderLoading"
            :disabled="!selectedAddressId"
          >
            确认下单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      searchText: '',
      loading: false,
      dishes: [],
      defaultImage: 'https://via.placeholder.com/300x200?text=菜品图片',
      
      // 购买对话框相关数据
      purchaseDialogVisible: false,
      selectedDish: null,
      quantity: 1,
      userAddresses: [],
      selectedAddressId: null,
      orderLoading: false
    }
  },
  computed: {
    filteredDishes() {
      if (!this.searchText) return this.dishes
      const query = this.searchText.toLowerCase()
      return this.dishes.filter(d => 
        d.dishName.toLowerCase().includes(query) || 
        (d.description && d.description.toLowerCase().includes(query))
      )
    }
  },
  mounted() {
    this.fetchDishes();
    this.fetchUserAddresses();
  },
  methods: {
    async fetchDishes() {
      this.loading = true
      try {
        const response = await axios.get('http://localhost:8081/dishes/all')
        this.dishes = response.data || []
      } catch (error) {
        console.error('获取菜品失败:', error)
        ElMessage.error('获取菜品失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchUserAddresses() {
      const userId = localStorage.getItem('userId');
      if (!userId) return;
      
      try {
        const response = await axios.get(`http://localhost:8081/addresses/${userId}`);
        this.userAddresses = response.data || [];
        // 如果有默认地址，则自动选中
        const defaultAddress = this.userAddresses.find(a => a.isDefault);
        if (defaultAddress) {
          this.selectedAddressId = defaultAddress.addressId;
        }
      } catch (error) {
        console.error('获取用户地址失败:', error);
        ElMessage.error('获取地址失败');
      }
    },
    
    handleSearch() {
      // 搜索功能通过computed属性自动处理
    },
    
    showPurchaseDialog(dish) {
      const userId = localStorage.getItem('userId');
      if (!userId) {
        ElMessage.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      this.selectedDish = dish;
      this.quantity = 1;
      this.purchaseDialogVisible = true;
    },
    
    async confirmPurchase() {
      if (!this.selectedAddressId) {
        ElMessage.warning('请选择配送地址');
        return;
      }
      
      try {
        this.orderLoading = true;
        
        const selectedAddress = this.userAddresses.find(a => a.addressId === this.selectedAddressId);
        if (!selectedAddress) {
          ElMessage.error('无效的配送地址');
          return;
        }
        
        // 创建订单
        const orderData = {
          userId: parseInt(localStorage.getItem('userId')),
          totalAmount: this.selectedDish.price * this.quantity,
          deliveryLocation: selectedAddress.specificLocation
        };
        
        const response = await axios.post('http://localhost:8081/orders/create', orderData);
        
        if (response.data.code === 200) {
          ElMessage.success('下单成功');
          this.purchaseDialogVisible = false;
        } else {
          throw new Error(response.data.message || '下单失败');
        }
      } catch (error) {
        console.error('下单失败:', error);
        ElMessage.error(error.message || '下单失败，请重试');
      } finally {
        this.orderLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.dish-container {
  padding: 12px;
}

.search-bar {
  margin-bottom: 15px;
}

.search-bar input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.dish-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.dish-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.dish-card:hover {
  transform: translateY(-5px);
}

.dish-image {
  width: 100%;
  height: 120px;
  background-size: cover;
  background-position: center;
}

.dish-info {
  padding: 10px;
}

.dish-info h3 {
  margin: 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dish-price {
  margin: 5px 0 0;
  color: #ff6700;
  font-weight: bold;
}

.loading, .empty {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 购买对话框样式 */
.purchase-dialog {
  padding: 10px;
}

.dish-info {
  display: flex;
  margin-bottom: 15px;
}

.dialog-dish-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 15px;
}

.dish-details {
  flex: 1;
}

.dish-details h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.price {
  color: #ff6700;
  font-weight: bold;
  margin: 5px 0;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

@media (max-width: 375px) {
  .dish-list {
    grid-template-columns: 1fr;
  }
  
  .dish-info {
    flex-direction: column;
  }
  
  .dialog-dish-image {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style>